extends ../base.pug

block title
  title 智能麻将战绩

block stylesheets
  link(rel="stylesheet", href="/css/match-share.css")

block body
  if match
    .match-share
      .match__body
        .match__game
          span.game__title 总局数：
          span.game__count #{match.gameCount || 0}
        .match__duration
          span.duration__title 总时长：
          span.duration__text #{match.durationFormat}
        .match__graph
          each player, index in match.players
              if player.avatar
                .block(class='block__' + (index + 1))
                  img(src=player.avatar, alt="avatar")
              else
                .block.block--empty.no-select(class='block__' + (index + 1))
                  | #{player.name.substring(0, 1)}
          .line.line__1.line__slash
            span 1
          .line.line__2.line__slash
            span 2
          .line.line__3.line__slash
            span 3
          .line.line__4.line__slash
            span 4
          .line.line__5.line__diagonal
            span 5
          .line.line__6.line__diagonal
            span 6


      .match__results
        .match__players
          each player in match.players
            .match__player
              if player.avatar
                .player__avatar
                  img(src=player.avatar, alt="avatar")
              else
                .player__avatar.no-select.player__avatar--empty #{player.name.substring(0, 1)}
              div.column
                .row
                  .player__name #{player.name}
                  if player.score >= 0
                    .player__score.player__score--positive +#{player.score}
                  else
                    .player__score.player__score--negative #{player.score}
                .row
                  span.detail__item 胡：#{player.huSum || 0}
                  span.detail__item 杠：#{player.gangSum || 0}
                  span.detail__item 查叫：#{player.chajiaoSum || 0}
              .row.player__badges
                if player.bigWinner
                  .badge__item.badge__crocodile
                    img(src="/images/icon_crocodile@2x.png", alt="badge")
                else if player.singleBigWinner
                  .badge__item.badge__star
                    img(src="/images/icon_star@2x.png", alt="badge")
                else if player.bigLoser
                  .badge__item.badge__rabbit
                    img(src="/images/icon_rabbit@2x.png", alt="badge")
                else
                  .badge__item
    .modal__overlay
      .modal__content
        .modal__action
          button.action__close &times;
        .modal__header 温馨提示
        .modal__body
          .modal__pics.pics__crocodile
            .pic_item
              img(src="/images/img_crocodile@2x.png", alt="meteor pic")
            .pic_item
              | 大鳄
            .modal__desc 即本场牌局的大赢家
          .modal__pics.pics__star
            .pic_item
              img(src="/images/img_star@2x.png", alt="meteor pic")
            .pic_item
              | 流星
            .modal__desc 即本场牌局单次赢最多的玩家
          .modal__pics.pics__rabbit
            .pic_item
              img(src="/images/img_rabbit@2x.png", alt="meteor pic")
            .pic_item
              | 肥兔
            .modal__desc 即本场牌局被宰最多的玩家

  script.
    (function() {
      //- polyfill
      if (!Array.isArray) {
        Array.isArray = function(arg) {
          return Object.prototype.toString.call(arg) === '[object Array]'
        }
      }
    }())

    window.players = !{JSON.stringify(match && match.players || [])} // Inject

    ;(function() {
      if (!window.players.length) return

      var body = document.querySelector('body')
      var modalEl = document.querySelector('.modal__overlay')
      var closeEl = document.querySelector('.action__close')
      var crocodileBadgeEls = list(document.querySelectorAll('.badge__crocodile'))
      var starBadgeEls = list(document.querySelectorAll('.badge__star'))
      var rabbitBadgeEls = list(document.querySelectorAll('.badge__rabbit'))
      // reldation line
      var lineEls = list(document.querySelectorAll('.line'))
      // slash
      var lineOne = lineEls[0]
      var lineTwo = lineEls[1]
      var lineThree = lineEls[2]
      var lineFour = lineEls[3]
      // diagonal
      var lineFive = lineEls[4]
      var lineSix = lineEls[5]

      console.log(window.players)

      for (var i = 0; i < crocodileBadgeEls.length; i++) {
        crocodileBadgeEls[i].onclick = function() {
          body.className = 'modal--open'
          modalEl.className = 'modal__overlay modal--crocodile'
        }
      }

      for (var i = 0; i < starBadgeEls.length; i++) {
        starBadgeEls[i].onclick = function() {
          body.className = 'modal--open'
          modalEl.className = 'modal__overlay modal--star'
        }
      }

      for (var i = 0; i < rabbitBadgeEls.length; i++) {
        rabbitBadgeEls[i].onclick = function() {
          body.className = 'modal--open'
          modalEl.className = 'modal__overlay modal--rabbit'
        }
      }

      //- First player  (1, 4, 5) -- (2, 3, 4)
      //- second player (1, 2, 6)

      var drawLines = []
      draw()

      closeEl.onclick = function() {
        body.className = ''
        modalEl.className = 'modal__overlay'
      }

      function draw() {
        for (var i = 0; i < players.length; i++) {
          var player = players[i]
          var keys = pickStartWith(Object.keys(player), 'scorefrom_')
          //- console.log(keys)
          console.log(player.name, player.score)
          for (var j = 0; j < keys.length; j++) {
            var key = keys[j]
            var nameAndId = splitNameandId(key)
            var name = nameAndId[0]
            var id = nameAndId[1]
            var score = player[key]

            if (!isDraw(drawLines, player.id, id)) {
              drawLines.push([player.id, id])

              i === 0 && drawPlayerOne(id, players, score)
              i === 1 && drawPlayerTwo(id, players, score)
              i === 2 && drawPlayerThree(id, players, score)
              i === 3 && drawPlayerFour(id, players, score)
            }
          }
        }
      }

      function drawPlayerOne(id, players, score) {
        if (id === players[1].id) {
          drawLine(lineOne, score)
        }

        if (id === players[2].id) {
          drawLine(lineFive, score, true)
        }

        if (id === players[3].id) {
          drawLine(lineFour, score, true)
        }
      }

      function drawPlayerTwo(id, players, score) {
        if (id === players[0].id) {
          drawLine(lineOne, score, true)
        }

        if (id === players[2].id) {
          drawLine(lineTwo, score)
        }

        if (id === players[3].id) {
          drawLine(lineSix, score, true)
        }
      }

      function drawPlayerThree(id, players, score) {
        if (id === players[0].id)  {
          drawLine(lineFive, score)
        }

        if (id === players[1].id)  {
          drawLine(lineTwo, score, true)
        }

        if (id === players[3].id)  {
          drawLine(lineThree, score)
        }
      }

      function drawPlayerFour(id, players, score) {
        if (id === players[0].id)  {
          drawLine(lineFour, score)
        }

        if (id === players[1].id)  {
          drawLine(lineSix, score)
        }

        if (id === players[2].id) {
          drawLine(lineThree, score)
        }
      }

      function drawLine(el, score, needToCorrect) {
        if (needToCorrect) {
          score *= -1
        }

        if (score > 0) {
          el.className = el.className + ' line--backward'
        } else if (score < 0) {
          el.className = el.className + ' line--forward'
        } else {
          //- el.className = el.className + ' line--twoway'
        }

        el.querySelector('span').textContent = Math.abs(score) || ''
      }

      function pickStartWith (arr, str) {
        var out = []

        for (var i = 0; i < arr.length; i++) {
          if (arr[i].indexOf(str) === 0) {
            out.push(arr[i])
          }
        }

        return out
      }

      function splitNameandId (str) {
        var out = []
        var source = str.split('_').slice(1)

        out = [ source.slice(0, -1).join('_'),  source.pop()]

        return out
      }

      function isDraw(arr, one, two) {
        if (!Array.isArray(arr)) return false

        for (var i = 0; i < arr.length; i++) {
            var tempArr = arr[i]
            if (Array.isArray(tempArr) && tempArr.indexOf(one) !== -1 && tempArr.indexOf(two) !== -1) {
              return true
            }
        }

        return false
      }

      function list(arrayLike) {
        return Array.prototype.slice.apply(arrayLike);
      }
    }())
  script(src="//unpkg.com/axios@0.16.2/dist/axios.min.js")
  script(src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js")
  script.
    (function() {
      function getResponseData(response) {
        return response.data
      }

      function getDesc (players) {
        var out = []
        for (var i = 0; i < players.length; i++) {
          var player = players[i]
          out.push(player.name + '：' + formatDigital(player.score))
        }

        return out.join('，')
      }

      function formatDigital (num) {
        return num > 0 ? '+' + num : num
      }

      function getOrigin() {
        return location.origin
      }

      function getIcon() {
        return getOrigin() + '/images/icon.png'
      }

      function getCurrentURL(stripHash) {
        if (stripHash) {
          return location.href.split('#')[0]
        }

        return location.href
      }

      axios
        .get('/wechat/sign?link=' + getCurrentURL(true))
        .then(getResponseData)
        .then(function (config) {
          wxReady(config)
        })
        .catch(function (error) {
          console.log(error)
        })

      function wxReady(config) {
        wx.config({
            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
            appId: config.appid, // 必填，公众号的唯一标识
            timestamp: config.timestamp, // 必填，生成签名的时间戳
            nonceStr: config.nonceStr, // 必填，生成签名的随机串
            signature: config.signature,// 必填，签名，见附录1
            jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
        });

        wx.ready(function () {
          wx.onMenuShareAppMessage({
            title: '智能麻将战绩',
            desc: getDesc(window.players),
            link: getCurrentURL(),
            imgUrl: getIcon(),
            type: 'link'
          })

          wx.onMenuShareTimeline({
              title: '智能麻将战绩', // 分享标题
              link: getCurrentURL(), // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
              imgUrl: getIcon(), // 分享图标
          });
        })
      }
    }())
